import Input from '@/component/Input'
import NavBar from '@/component/Nav'
import Textarea from '@/component/Textarea'
import { TypeState } from '@/store'
import { editPersonProflie, getPersonData, signoutFn, updatePersonPhoto } from '@/store/action/user'
import { PersonData } from '@/store/reducer/user'
import history from '@/utils/history'
import { removeTokenInfo } from '@/utils/storage'
import { List, Popup, Toast, DatePicker, Dialog } from 'antd-mobile'
import dayjs from 'dayjs'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './index.module.scss'

export default function ProfileEdit() {
  const dispatch = useDispatch()
  const { personData } = useSelector((state: TypeState) => state.user)
  type VisibleBool = {
    visibleBool: boolean
    type: 'photo' | 'gender' | ''
  }
  type VisibleBoolright = {
    visibleBool: boolean
    type: 'intro' | 'name' | ''
  }
  const [visibleBool, setVisibleBool] = useState<VisibleBool>({ visibleBool: false, type: '' })
  const [RightVisibleBool, setRightVisibleBool] = useState<VisibleBoolright>({ visibleBool: false, type: '' })
  useEffect(() => {
    // 获取个人资料
    dispatch(getPersonData())
  }, [dispatch])
  // 打开弹窗的函数
  const PopCloseWindows = () => {
    setVisibleBool({ visibleBool: false, type: '' })
    setRightVisibleBool({ visibleBool: false, type: '' })
  }
  const getImg = useRef<HTMLInputElement>(null)
  const handleChangImg = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const pt = new FormData()
      pt.append('photo', e.target.files[0])
      // 提交fordata(图片)数据到后台
      dispatch(updatePersonPhoto(pt))
    }
    Toast.show({ content: '更新成功' })
    // 更新完之后关闭弹窗
    PopCloseWindows()
  }
  // 更改昵称、生日、性别等
  const updateUserGender = (data: Partial<PersonData>) => {
    dispatch(editPersonProflie(data))
    // 提示用户
    Toast.show({ content: '更新成功' })
    // 关闭窗口
    PopCloseWindows()
  }
  // 通过受控表单拿到name值
  const [nickename, setNickName] = useState('')
  // 收集个人简介的value
  const [intro, setIntro] = useState('')

  const popWindowSetName = (type: 'name' | 'intro') => {
    if (type === 'name') {
      if (personData.name) {
        setNickName(personData.name)
      }
    } else if (type === 'intro') {
      if (personData.intro) {
        setIntro(personData.intro)
      }
    }
    setRightVisibleBool({ visibleBool: true, type: type })
  }
  // 点击提交
  const handleSubmit = () => {
    if (RightVisibleBool.type === 'name') {
      // 提交昵称

      updateUserGender({ name: nickename })
    } else if (RightVisibleBool.type === 'intro') {
      // 提交简介更新
      updateUserGender({ intro })
    }
  }
  // 回车提交
  const handleKeyup = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      updateUserGender({ name: nickename })
    }
  }
  const [visibleDate, setVisibleDate] = useState(false)
  // 点击确认时间选择
  const handleBirthdayConfim = (value: Date) => {
    const birthday = dayjs(value).format('YYYY-MM-DD')
    // 向后台发送更新生日日期
    updateUserGender({ birthday })
    // 提示更新成功
    Toast.show({ content: '更新成功' })
  }
  // 登出
  const signOut = () => {
    Dialog.confirm({
      cancelText: '我再想想',
      confirmText: '狠心退出',
      title: '温馨提示',
      content: '是否退出登录？',
      onConfirm: () => {
        // 清除本地的token
        removeTokenInfo()
        // 清空储存在redux的token信息
        dispatch(signoutFn())
        // 跳转到登录页面
        history.push('/login')
        // 提示用户
        Toast.show({ content: '退出成功' })
      },
    })
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              onClick={() => setVisibleBool({ visibleBool: true, type: 'photo' })}
              arrow
              extra={<img className="avatar" src={personData.photo} alt="" />}
            >
              头像
            </List.Item>

            <List.Item onClick={() => popWindowSetName('name')} arrow extra={personData.name}>
              昵称
            </List.Item>

            <List.Item
              onClick={() => popWindowSetName('intro')}
              arrow
              extra={<span className="intro">{personData.intro}</span>}
            >
              简介
            </List.Item>

            <List.Item
              onClick={() => setVisibleBool({ visibleBool: true, type: '' })}
              arrow
              extra={personData.gender === 0 ? '男' : '女'}
            >
              性别
            </List.Item>
            <List.Item onClick={() => setVisibleDate(true)} arrow extra={personData.birthday}>
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            accept=".png,.jpg"
            onChange={(e) => handleChangImg(e)}
            ref={getImg}
            className="avatar-upload"
            type="file"
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button onClick={signOut} className="btn">
            退出登录
          </button>
        </div>
      </div>
      {/* 底部弹出层 */}
      <Popup
        onMaskClick={() => setVisibleBool({ visibleBool: false, type: '' })}
        visible={visibleBool.visibleBool}
        position="bottom"
        bodyClassName="popup-bottom-list"
      >
        {visibleBool.type === 'photo' ? (
          <>
            <div onClick={() => getImg.current?.click()} className="list-item">
              拍照
            </div>
            <div onClick={() => getImg.current?.click()} className="list-item">
              本地选择
            </div>
          </>
        ) : (
          <>
            <div onClick={() => updateUserGender({ gender: 0 })} className="list-item">
              男
            </div>
            <div onClick={() => updateUserGender({ gender: 1 })} className="list-item">
              女
            </div>
          </>
        )}

        <div onClick={() => setVisibleBool({ visibleBool: false, type: '' })} className="list-item">
          取消
        </div>
      </Popup>
      {/* 右侧弹出层 */}
      <Popup
        // 不可见时卸载内容，用于配合加载表单的时候自动获取焦点
        destroyOnClose
        visible={RightVisibleBool.visibleBool}
        position="right"
        bodyClassName="popup-right"
      >
        <NavBar
          onBack={() => setRightVisibleBool({ type: '', visibleBool: false })}
          right={<span onClick={handleSubmit}>提交</span>}
        >
          {RightVisibleBool.type === 'intro' ? '编辑用户简介' : '编辑用户昵称'}
        </NavBar>
        <div className="edit-content">
          {RightVisibleBool.type === 'intro' ? (
            <>
              {' '}
              <h3 className="edit-title">编辑简介</h3>
              <Textarea value={intro} onChange={(e) => setIntro(e.target.value)} maxLength={10} />
            </>
          ) : (
            <>
              {' '}
              <h3 className="edit-title">编辑昵称</h3>
              <Input
                onKeyUp={(e) => handleKeyup(e)}
                onChange={(e) => setNickName(e.target.value)}
                value={nickename}
                autoFocus
                type="text"
                className="edit-input"
              />
            </>
          )}
        </div>
      </Popup>
      {/* 日期选择器 */}
      <DatePicker
        onClose={() => setVisibleDate(false)}
        onConfirm={(e) => handleBirthdayConfim(e)}
        min={new Date('1920-05-10')}
        max={new Date()}
        visible={visibleDate}
      ></DatePicker>
    </div>
  )
}
